package com.weetop.aklyscan.activity;

import static android.app.Activity.RESULT_OK;

import android.Manifest;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothProfile;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.classic.adapter.BaseAdapterHelper;
import com.classic.adapter.CommonRecyclerAdapter;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnSelectListener;
import com.qmuiteam.qmui.layout.QMUIButton;
import com.weetop.aklyscan.R;
import com.weetop.aklyscan.activity.lanya.BluetoothLeClass;
import com.weetop.aklyscan.activity.lanya.Bluetooth_Scale;
import com.weetop.aklyscan.activity.lanya.DeviceListActivity;
import com.weetop.aklyscan.activity.lanya.PubFunction;
import com.weetop.aklyscan.appConfig.GlideImageLoader;
import com.weetop.aklyscan.appConfig.MyApplication;
import com.weetop.aklyscan.base.BaseFragment;
import com.weetop.aklyscan.base.BaseUrl;
import com.weetop.aklyscan.base.mvp.BaseModel;
import com.weetop.aklyscan.bean.KuaiDiBean;
import com.weetop.aklyscan.bean.KuaiDiImgBean;
import com.weetop.aklyscan.bean.LogisticsBean;
import com.weetop.aklyscan.bean.MailBean;
import com.weetop.aklyscan.bean.MailBean1;
import com.weetop.aklyscan.bean.MailNumberBean;
import com.weetop.aklyscan.bean.OrderDetailBean;
import com.weetop.aklyscan.bean.OrderDetailShowBean;
import com.weetop.aklyscan.presenter.SendOutPresent;
import com.weetop.aklyscan.utils.widget.MyDialogUtil;
import com.weetop.aklyscan.view.SendOutView;

import org.angmarch.views.NiceSpinner;
import org.angmarch.views.OnSpinnerItemSelectedListener;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import ZPL.ZPLPrinterHelper;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import cc.shinichi.library.tool.utility.ui.ToastUtil;

public class Fragment_send_out extends BaseFragment<SendOutPresent> implements SendOutView {
    private static final int HUOJIA_CODE = 12000;
    private static final int REQUEST_HUOJIA_CODE_SCAN_ONE = 22000;
    Unbinder unbinder;

    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.recycler)
    RecyclerView recycler;
    @BindView(R.id.orderid)
    TextView orderid;
    @BindView(R.id.orderid1)
    TextView orderid1;
    @BindView(R.id.bingdan_ll)
    LinearLayout bingdan_ll;
    @BindView(R.id.send_out_type)
    TextView send_out_type;
    @BindView(R.id.userInfo)
    TextView userInfo;
    @BindView(R.id.content)
    TextView content;
    @BindView(R.id.num)
    TextView num;
    @BindView(R.id.chanpin_dx)
    TextView chanpin_dx;
    @BindView(R.id.chanpin_zl)
    TextView chanpin_zl;
    @BindView(R.id.sjzl)
    TextView sjzl;
    @BindView(R.id.order_type)
    TextView order_type;
    @BindView(R.id.spinner)
    NiceSpinner spinner;
    @BindView(R.id.mailName)
    TextView mailName;
    @BindView(R.id.mailCode)
    TextView mailCode;
    @BindView(R.id.qingkong3)
    TextView qingkong3;
    @BindView(R.id.shengcheng)
    TextView shengcheng;
    @BindView(R.id.lianjie)
    TextView lianjie;
    @BindView(R.id.mail_code_ll1)
    LinearLayout mail_code_ll1;
    @BindView(R.id.mail_code_ll2)
    LinearLayout mail_code_ll2;
    @BindView(R.id.mail_code1)
    TextView mail_code1;
    @BindView(R.id.mail_code2)
    TextView mail_code2;
    @BindView(R.id.btn_save)
    QMUIButton btnSave;
    @BindView(R.id.dayin_img)
    ImageView dayin_img;
    @BindView(R.id.lvDevices)
    ListView lvDevices;
    @BindView(R.id.th_ll)
    LinearLayout th_ll;
    @BindView(R.id.iv_bluetooth_status)
    ImageView iv_bluetooth_status;
    private CommonRecyclerAdapter<OrderDetailBean.DataBean> adapter;
    private List<OrderDetailBean.DataBean> list = new ArrayList<>();
    private CommonRecyclerAdapter<OrderDetailBean.DataBean1> adapter2;
    private List<OrderDetailBean.DataBean1> list2 = new ArrayList<>();
    private List<OrderDetailBean.DataBean1> th_data = new ArrayList<>();
    private List<MailBean.DataBean> mailList = new ArrayList<>();
    private List<MailBean1.DataBean> mailList1 = new ArrayList<>();
    private KuaiDiBean kuaiDiBean;

    private String orderCode, orderID, name, mobile, address;
    public static String templateCode, mailCode1, mailID1 = "";
    public int oldSjzl = 0;
    public String imgUrl = "";
    private boolean isBing, dyjStatus;
    private String[] scfs;
    private String thStatus = "";
    private boolean select = false;

    Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                for (int i = 0; i < list.size(); i++) {
                    if (list.get(i).getSerial_code().equals(msg.obj.toString())) {
                        if ("-1".equals(thStatus)) {
                            for (OrderDetailBean.DataBean1 bean : list2) {
//                                if (Integer.parseInt(bean.getRetreat_num()) > 0) {
//                                    if (isTh(bean.getGoods_model(), Integer.parseInt(bean.getRetreat_num()))) {
                                showError(bean.getGoods_model() + "有退货未处理");
                                return;
//                                    }
//                                }
                            }
                        }

                        if (list.get(i).isSelect()) {
                            playRing("chongfu.mp3");
                            return;
                        }
                        playRing("shujuyouxiao.mp3");
                        list.get(i).setSelect(true);
                        adapter.notifyDataSetChanged();
                        return;
                    }
                    if (i == list.size() - 1) {
                        playRing("shibai.mp3");
                    }
                }
            } else if (msg.what == 2) {
                mPresenter.updateOrder(orderCode);
            } else if (msg.what == 3) {
                if (TextUtils.isEmpty(kuaiDiBean.getImgBase64())) {
                    mPresenter.getKuaiDiImg("1", orderCode, kuaiDiBean.getKuaidinum());
                }
            }
        }
    };

    Handler handler1 = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                getDayinStatus();
                handler1.sendEmptyMessageDelayed(1, 3000);
            } else if (msg.what == 2) {
                if (MyApplication.b_scaleIsConnect) {
                    iv_bluetooth_status.setImageResource(R.mipmap.bluetooth_true);
                    if (MyApplication.isBluePlay == 0 || MyApplication.isBluePlay == 2) {
                        MyApplication.isBluePlay = 1;
                        playRing("lianjiesuccess.mp3");
                    }
                } else {
                    iv_bluetooth_status.setImageResource(R.mipmap.bluetooth_error);
                    if (MyApplication.isBluePlay == 1) {
                        MyApplication.isBluePlay = 2;
                        playRing("lianjieerror.mp3");
                    }
                }
            }
        }
    };
    private BluetoothAdapter bluetoothAdapter;

    private BluetoothDevice btDevice = null;
    private BluetoothGatt mBluetoothGatt = null;

    @Override
    protected SendOutPresent createPresenter() {
        return new SendOutPresent(this, getActivity());
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = View.inflate(getActivity(), R.layout.fragment_send_out, null);
        unbinder = ButterKnife.bind(this, view);
        recyclerView.setLayoutManager(new LinearLayoutManager(mActivity));
        adapter = new CommonRecyclerAdapter<OrderDetailBean.DataBean>(mActivity, R.layout.item_send_out, list) {
            @Override
            public void onUpdate(BaseAdapterHelper helper, OrderDetailBean.DataBean item, int position) {
                if (StringUtils.equalsIgnoreCase(item.getIs_thrk(), "1")) {
                    helper.setBackgroundColor(R.id.item_layout, Color.RED);
                } else {
                    helper.setBackgroundRes(R.id.item_layout, R.drawable.tab_line);
                }

                helper.setText(R.id.tv_id, position + 1 + "");
                helper.setText(R.id.sn, item.getSerial_code());
                helper.setText(R.id.name, item.getGoods_name());
                helper.setText(R.id.model, item.getGoods_model());
                helper.setText(R.id.time, item.getGoods_cate());
                if (item.isSelect()) {
                    helper.setImageResource(R.id.select, R.mipmap.select_true);
                } else {
                    helper.setImageResource(R.id.select, R.color.transparent);
                }
            }
        };
        recyclerView.setAdapter(adapter);
        recycler.setLayoutManager(new LinearLayoutManager(mActivity));
        adapter2 = new CommonRecyclerAdapter<OrderDetailBean.DataBean1>(mActivity, R.layout.item_send_out_th, list2) {
            @Override
            public void onUpdate(BaseAdapterHelper helper, OrderDetailBean.DataBean1 item, int position) {
                helper.setText(R.id.tv_id, position + 1 + "");
                helper.setText(R.id.model, item.getGoods_model());
                helper.setText(R.id.num, item.getRetreat_num());
            }
        };
        recycler.setAdapter(adapter2);
        dayin_img.setVisibility(View.VISIBLE);
        order_type.setTag(0);
        mPresenter.mailType();
        mPresenter.mailType1();
        if (MyApplication.b_scaleIsConnect == Boolean.TRUE) {
            iv_bluetooth_status.setImageResource(R.mipmap.bluetooth_true);
        } else {
            iv_bluetooth_status.setImageResource(R.mipmap.bluetooth_error);
        }

        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (bluetoothAdapter != null) {
            if (bluetoothAdapter.isEnabled()) {
                Set<BluetoothDevice> bluetoothDevices = bluetoothAdapter.getBondedDevices();
                for (BluetoothDevice device : bluetoothDevices) {
                    //log打印蓝牙设备的名称和地址
                    Log.e("TAG", "decive name: " + device.getName());
                    Log.e("TAG", "device addr: " + device.getAddress());
                    if (device.getName().equals("KunhongScale30A")) {
//                        new Thread(new Runnable() {
//                            @Override
//                            public void run() {
//                                try{
//                                    final BluetoothSocket socket = (BluetoothSocket) device.getClass().
//                                            getDeclaredMethod("createRfcommSocket", new Class[]{int.class}).invoke(device, 1);
//                                    bluetoothAdapter.cancelDiscovery();
//                                    socket.connect();
//                                }catch (Exception e){
//                                    e.printStackTrace();
//                                }
//                            }
//                        }).start();
//                        bluetoothAdapter.getRemoteDevice(device.getAddress());
                        mBluetoothGatt = device.connectGatt(getActivity(), false, mGattCallback);
                    }
                }
            } else {
                ToastUtil.getInstance()._short(getActivity(), "未开启蓝牙");
            }
        } else {
            ToastUtil.getInstance()._short(getActivity(), "设备不支持蓝牙");
        }
        getBle();
        handler1.sendEmptyMessage(1);
//        onBarcodeEvent("XSDD20220210-00010");
//        handler1.postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                onBarcodeEvent("M1001akny022128C3598");
//            }
//        }, 2000);
        return view;
    }

    @Override
    public void getMailTypeSuccess(BaseModel<MailBean> o) {
        mailList = o.getData().getList_data();
        LogUtils.e(MyApplication.getMailCode(), order_type.getTag());
        if ((int) order_type.getTag() == 1) {
            for (int i = 0; i < mailList.size(); i++) {
                if (mailID1.equals(mailList.get(i).getId())) {
                    mailName.setText(mailList.get(i).getName());
                    mailCode.setText(mailList.get(i).getCode());
                    mailCode1 = mailList.get(i).getCode();
                    mailID1 = mailList.get(i).getId();
                    return;
                }

//                if (i == mailList1.size() - 1) {
//                    mailName.setText(mailList.get(0).getName());
//                    mailCode.setText(mailList.get(0).getCode());
//                    mailCode1 = mailList.get(0).getCode();
//                    mailID1 = mailList.get(0).getId();
//                }
            }
        }
    }

    @Override
    public void getMailType1Success(BaseModel<MailBean1> o) {
        mailList1 = o.getData().getList();
        LogUtils.e(MyApplication.getMailID(), order_type.getTag());
        if ((int) order_type.getTag() == 0) {
            for (int i = 0; i < mailList1.size(); i++) {
                if (mailID1.equals(mailList1.get(i).getId())) {
                    mailName.setText(mailList1.get(i).getSon_name());
                    mailCode1 = mailList1.get(i).getCode();
                    mailID1 = mailList1.get(i).getId();
                    templateCode = mailList1.get(i).getTemplate_code();
                    mPresenter.surplus(mailList1.get(i).getId());
                    return;
                }

                if (MyApplication.getMailID().equals(mailList1.get(i).getId())) {
                    mailName.setText(mailList1.get(i).getSon_name());
                    mailCode1 = mailList1.get(i).getCode();
                    mailID1 = mailList1.get(i).getId();
                    templateCode = mailList1.get(i).getTemplate_code();
                    mPresenter.surplus(mailList1.get(i).getId());
                    return;
                }


//                if (i == mailList1.size() - 1) {
//                    mailName.setText(mailList1.get(0).getSon_name());
//                    mailCode1 = mailList1.get(0).getCode();
//                    mailID1 = mailList1.get(0).getId();
//                    templateCode = mailList1.get(0).getTemplate_code();
//                    mPresenter.surplus(mailList1.get(0).getId());
//                }
            }
        }
    }

    @Override
    public void getInquirySuccess(BaseModel<LogisticsBean> o) {

    }

    @Override
    public void getEditShowSuccess(BaseModel<OrderDetailShowBean> o) {

    }

    @Override
    public void getInto37Success(BaseModel<String> o) {
        orderID = o.getData();
        if (!TextUtils.isEmpty(orderID)) {
            orderid.setText(orderCode);
            mPresenter.editShow(orderID);
        } else {
            ToastUtil.getInstance()._short(getActivity(), "订单不存在");
        }
    }

    @Override
    public void getInto38Success(BaseModel<String> o) {
        mPresenter.Into39(orderCode, "1");
    }

    boolean stopStatus = false;

    String all_count;

    @Override
    public void getInto39Success(BaseModel<OrderDetailBean> o) {
        OrderDetailBean dateBean = o.getData();
        select = false;
        thStatus = dateBean.getStatus();
        imgUrl = "";
        if ("2".equals(dateBean.getNew_order_type())) {
            select = true;
        }
        stopStatus = dateBean.getShop_status().equals("1");

        if ((dateBean.getSales_status().equals("1")) || (dateBean.getSales_status().equals("2") && dateBean.getBh_status().equals("1"))) {
            th_data.clear();
            if (o.getData().getTh_data().size() > 0) {
                th_data.addAll(o.getData().getTh_data());
            }
            if (o.getData().getItems().size() > 0) {
                list2.clear();
//                list2.addAll(o.getData().getItems());
                for (OrderDetailBean.DataBean1 dataBean1 : o.getData().getItems()) {
                    if (dataBean1.getWr_num() > 0)
                        list2.add(dataBean1);
                }
                if (list2.size() > 0) {
                    th_ll.setVisibility(View.VISIBLE);
                }
                adapter2.clear();
                adapter2.addAll(list2);
            } else {
                th_ll.setVisibility(View.GONE);
            }

            if (dateBean.getBh_type().equals("1")) {
                ToastUtil.getInstance()._short(getActivity(), "订单状态异常");
                playRing("shujuwuxiao.mp3");
                return;
            }
            orderid.setText(orderCode);
            orderid.setBackgroundResource(R.drawable.et_grey);
            playRing("shujuyouxiao.mp3");
            if (dateBean.getItems_two() != null && dateBean.getItems_two().size() != 0) {
                isBing = true;
                bingdan_ll.setVisibility(View.VISIBLE);
                orderid1.setText(dateBean.getMerger_order_sn());
            } else {
                isBing = false;
                bingdan_ll.setVisibility(View.GONE);
            }

            userInfo.setText(dateBean.getExpress_user_name() + " " + dateBean.getExpress_user_tel() + "\n" +
                    dateBean.getExpress_address());
            content.setText(dateBean.getOrder_details());
            num.setText(dateBean.getAll_count());
            all_count = dateBean.getAll_count();
            if (!TextUtils.isEmpty(dateBean.getTotal_weight())) {
                chanpin_zl.setText(dateBean.getTotal_weight() + "g");
            } else {
                chanpin_zl.setText("");
            }
            name = dateBean.getExpress_user_name();
            mobile = dateBean.getExpress_user_tel();
            address = dateBean.getExpress_address();
            orderID = dateBean.getOrder_id();
            shengcheng.setVisibility(View.VISIBLE);
            mailCode.setVisibility(View.VISIBLE);
            qingkong3.setVisibility(View.VISIBLE);
            List<String> spinnerList = new ArrayList<String>();
            if (dateBean.getBh_status().equals("1")) {
                send_out_type.setText("补发");
                list.clear();
                for (OrderDetailBean.DataBean bean : o.getData().getItems_three()) {
                    boolean isSet = false;
                    if ("-1".equals(thStatus)) {
                        for (OrderDetailBean.DataBean1 bean1 : list2) {
                            if (bean.getGoods_model().equals(bean1.getGoods_model()) && Integer.parseInt(bean1.getRetreat_num()) > 0) {
//                                if (isTh(bean.getGoods_model(), Integer.parseInt(bean1.getRetreat_num()))) {
//                                    showError(bean1.getGoods_model() + "有退货未处理");
                                isSet = true;
                                bean.setTh(true);
//                                bean.setSelect(true);
//                                }
                            }
                        }
                    }
                    if (!isSet)
                        bean.setSelect(select);
                    LogUtils.e(bean.getIs_thrk(), bean.getSerial_code());
                    if (StringUtils.equalsIgnoreCase(bean.getIs_thrk(), "1")) {
                        bean.setSelect(true);
                    }
                }
                list.addAll(o.getData().getItems_three());
                adapter.clear();
                adapter.addAll(list);
                scfs = new String[]{"系统生成"};
                spinnerList.add("系统生成");
            } else {
                if (dateBean.getMerger_status().equals("0")) {
                    send_out_type.setText("首发");
                    spinnerList.add("系统生成");
                    spinnerList.add("手动填写");
                    scfs = new String[]{"系统生成", "手动填写"};
                    list.clear();
                    for (OrderDetailBean.DataBean bean : o.getData().getItems_one()) {
                        boolean isSet = false;
                        if ("-1".equals(thStatus)) {
                            for (OrderDetailBean.DataBean1 bean1 : list2) {
                                if (bean.getGoods_model().equals(bean1.getGoods_model()) && Integer.parseInt(bean1.getRetreat_num()) > 0) {
//                                    if (isTh(bean.getGoods_model(), Integer.parseInt(bean1.getRetreat_num()))) {
//                                    showError(bean1.getGoods_model() + "有退货未处理");
                                    isSet = true;
                                    bean.setTh(true);
//                                    }
//                                    bean.setSelect(true);
//                                }
                                }
                            }
                        }
                        if (!isSet)
                            bean.setSelect(select);

                        if (StringUtils.equalsIgnoreCase(bean.getIs_thrk(), "1")) {
                            bean.setSelect(true);
                        }
                    }
                    list.addAll(o.getData().getItems_one());
                    adapter.clear();
                    adapter.addAll(list);
                } else {
                    send_out_type.setText("并发");
                    list.clear();

                    if ("2".equals(o.getData().getPartner_type())) {
                        spinnerList.add("手动填写");
                        order_type.setText("手动填写");
                        scfs = new String[]{"手动填写"};
                        mail_code_ll1.setVisibility(View.GONE);
                        mail_code_ll2.setVisibility(View.VISIBLE);
                        btnSave.setText("发货保存");
                        btnSave.setVisibility(View.VISIBLE);
                        dayin_img.setVisibility(View.GONE);
                        order_type.setTag(1);
                    } else {
                        spinnerList.add("系统生成");
                        order_type.setText("系统生成");
                        scfs = new String[]{"系统生成"};
                        order_type.setTag(0);
                        mail_code_ll1.setVisibility(View.GONE);
                        mail_code_ll2.setVisibility(View.VISIBLE);
                        btnSave.setText("发货保存");
                        btnSave.setVisibility(View.VISIBLE);
                        dayin_img.setVisibility(View.GONE);
                    }
                    if (!TextUtils.isEmpty(o.getData().getExpress_sn())) {
                        order_type.setEnabled(false);
                        mailName.setEnabled(false);
                        shengcheng.setVisibility(View.INVISIBLE);
                        mailCode.setVisibility(View.INVISIBLE);
                        qingkong3.setVisibility(View.INVISIBLE);
                    }
                    if (!StringUtils.isEmpty(o.getData().getMerger_two_actual_weight()))
                        oldSjzl = Integer.parseInt(o.getData().getMerger_two_actual_weight().replace("g", ""));
                    if (!StringUtils.isEmpty(o.getData().getExpress_images())) {
                        imgUrl = o.getData().getExpress_images();
                    }

                    int oldWeight = 0;
                    if (!StringUtils.isEmpty(o.getData().getCount_shop_weight())) {
                        oldWeight = Integer.parseInt(o.getData().getCount_shop_weight().replace("g", ""));
                    }
//                    int newWeight = 0;
//                    if (!StringUtils.isEmpty(o.getData().getTotal_weight())) {
//                        newWeight = Integer.parseInt(o.getData().getTotal_weight().replace("g", ""));
//                    }
                    chanpin_zl.setText((oldWeight) + "g");
                    mail_code2.setText(o.getData().getExpress_sn());
                    mailName.setText(o.getData().getExpress_name());
                    for (OrderDetailBean.DataBean bean : o.getData().getItems_one()) {
                        boolean isSet = false;
                        if ("-1".equals(thStatus)) {
                            for (OrderDetailBean.DataBean1 bean1 : list2) {
                                if (bean.getGoods_model().equals(bean1.getGoods_model()) && Integer.parseInt(bean1.getRetreat_num()) > 0) {
//                                    if (isTh(bean.getGoods_model(), Integer.parseInt(bean1.getRetreat_num()))) {
//                                    showError(bean1.getGoods_model() + "有退货未处理");
                                    isSet = true;
                                    bean.setTh(true);
//                                    }
//                                    bean.setSelect(true);
//                                }
                                }
                            }
                        }
                        if (!isSet)
                            bean.setSelect(select);
                        if (StringUtils.equalsIgnoreCase(bean.getIs_thrk(), "1")) {
                            bean.setSelect(true);
                        }
                    }
                    list.addAll(o.getData().getItems_one());
                    if (o.getData().getItems_two() != null) {
                        for (OrderDetailBean.DataBean bean : o.getData().getItems_two()) {
                            boolean isSet = false;
                            if ("-1".equals(thStatus)) {
                                for (OrderDetailBean.DataBean1 bean1 : list2) {
                                    if (bean.getGoods_model().equals(bean1.getGoods_model()) && Integer.parseInt(bean1.getRetreat_num()) > 0) {
//                                        if (isTh(bean.getGoods_model(), Integer.parseInt(bean1.getRetreat_num()))) {
//                                    showError(bean1.getGoods_model() + "有退货未处理");
                                        isSet = true;
                                        bean.setTh(true);
//                                        }
//                                        bean.setSelect(true);
//                                }
                                    }
                                }
                            }
                            LogUtils.e(bean.isSelect(), bean.getSerial_code());
                            if (!isSet)
                                bean.setSelect(select);
                            if (StringUtils.equalsIgnoreCase(bean.getIs_thrk(), "1")) {
                                bean.setSelect(true);
                            }
                        }
                        list.addAll(o.getData().getItems_two());
                    }
                    adapter.clear();
                    adapter.addAll(list);
                }
            }


            spinner.attachDataSource(spinnerList);
            spinner.setOnSpinnerItemSelectedListener(new OnSpinnerItemSelectedListener() {
                @Override
                public void onItemSelected(NiceSpinner parent, View view, int position, long id) {
                    order_type.setTag(position);
                    if (position == 0) {
                        mail_code_ll1.setVisibility(View.VISIBLE);
                        mail_code_ll2.setVisibility(View.GONE);
                        btnSave.setText("发货打印");
                        btnSave.setVisibility(View.GONE);

                        for (int i = 0; i < mailList1.size(); i++) {
                            if (MyApplication.getMailID().equals(mailList1.get(i).getId())) {
                                mailName.setText(mailList1.get(i).getSon_name());
                                mailCode1 = mailList1.get(i).getCode();
                                mailID1 = mailList1.get(i).getId();
                                templateCode = mailList1.get(i).getTemplate_code();
                                mPresenter.surplus(mailList1.get(i).getId());
                                return;
                            }
                        }
                    } else {
                        mail_code_ll1.setVisibility(View.GONE);
                        mail_code_ll2.setVisibility(View.VISIBLE);
                        btnSave.setText("发货保存");
                        btnSave.setVisibility(View.VISIBLE);
                        for (int i = 0; i < mailList.size(); i++) {
                            if (MyApplication.getMailCode().equals(mailList.get(i).getId())) {
                                mailName.setText(mailList.get(i).getName());
                                mailCode1 = mailList.get(i).getCode();
                                mailID1 = mailList.get(i).getId();
                                return;
                            }
                        }
                    }
                }
            });

            if (select) {
                send_out_type.setText("刷单");
                num.setText("");
                chanpin_zl.setText("");
            }
        } else if (dateBean.getSales_status().equals("2")) {
            ToastUtil.getInstance()._short(getActivity(), "订单已发货");
            playRing("yifahuo.mp3");
        } else {
            ToastUtil.getInstance()._short(getActivity(), "订单状态异常");
            playRing("shujuwuxiao.mp3");
        }
    }

    private boolean isTh(String model, int thNum) {
        if (th_data.size() == 0) return true;
        int total = 0;

        for (int i = 0; i < th_data.size(); i++) {
            if (model.equals(th_data.get(i).getGoods_model())) {
                total++;
            }
        }
        return total == thNum;
    }

    @Override
    public void getUpOrderSuccess(BaseModel<String> o) {
//        ToastUtil.getInstance()._short(getActivity(), "操作成功");
//        dayin_img.setVisibility(View.VISIBLE);
//        handler1.sendEmptyMessage(1);
        playRing("danhaochenggong.mp3");
//        if ((int) order_type.getTag() == 0) {
//            mPresenter.surplus(mailID1);
//        }
        mPresenter.mailType();
        mPresenter.mailType1();
        if ((int) order_type.getTag() == 1){
            clean();
        }
    }

    public void clean() {
        mail_code1.setText("");
        shengcheng.setEnabled(true);
        shengcheng.setVisibility(View.VISIBLE);
        chanpin_dx.setEnabled(true);
        lianjie.setEnabled(true);
        mailName.setEnabled(true);
        order_type.setEnabled(true);
        orderid.setText("");
        orderid.setBackgroundResource(R.drawable.et_yellow);
        list.clear();
        adapter.clear();
        adapter.notifyDataSetChanged();
        list2.clear();
        adapter2.clear();
        adapter2.notifyDataSetChanged();
        sjzl.setText("");
        chanpin_dx.setText("");
        mail_code2.setText("");
        isBing = false;
        bingdan_ll.setVisibility(View.GONE);
        orderid1.setText("");
        send_out_type.setText("");
        userInfo.setText("");
        content.setText("");
        num.setText("");
        all_count = "";
        chanpin_zl.setText("");
        name = "";
        mobile = "";
        address = "";
        orderID = "";
        orderCode = "";
    }

    @Override
    public void getBaiduTokenSuccess(BaseModel<String> o) {
        String imgUrl;
        if (kuaiDiBean.getImgBase64().contains("/public")) {
            imgUrl = BaseUrl.url1 + kuaiDiBean.getImgBase64().replace("/public", "");
        } else {
            imgUrl = BaseUrl.url1 + kuaiDiBean.getImgBase64();
        }
        mPresenter.distinguish(o.getData(), imgUrl, orderCode);
    }

    @Override
    public void getupdateOrderSuccess(BaseModel<String> o) {
        clean();
    }

    @Override
    public void getKuaiDiImgError() {
        playRing("tuxianghuoqushibai.mp3");
    }

    @Override
    public void getKuaiDiImgSuccess(BaseModel<KuaiDiImgBean> o) {
        if (TextUtils.isEmpty(o.getData().getImg_base64())) {
//            showLoading();
            playRing("tuxianghuoqushibai.mp3");
            handler.sendEmptyMessageDelayed(3, 3000);
        } else {
            hideLoading();
            playRing("tuxianghuoquchenggong.mp3");
            kuaiDiBean.setImgBase64(o.getData().getImg_base64());
            if (imgNull) {
                imgNull = false;
                if (stopStatus) {
                    mPresenter.baiduToken();
                }
            } else {
                daYin();
            }
        }
    }

    boolean imgNull = false;

    @Override
    public void getKuaiDiCodeSuccess(BaseModel<KuaiDiBean> o) {
        playRing("danhaochenggong.mp3");
        kuaiDiBean = o.getData();
        shengcheng.setEnabled(false);
        mail_code1.setText(kuaiDiBean.getKuaidinum());

        mPresenter.upOrder(orderID, mail_code1.getText().toString().trim(), sjzl.getText().toString().trim(), chanpin_dx.getText().toString().trim(),
                mailID1, "2", content.getText().toString().trim(), mailName.getText().toString().trim(),
                ((int) order_type.getTag() + 1) + "");
        if (TextUtils.isEmpty(kuaiDiBean.getImgBase64())) {
            imgNull = true;
//            showLoading();
//            playRing("tuxianghuoqushibai");
            handler.sendEmptyMessageDelayed(3, 3000);
        } else {
            dissmissDialog();
//            playRing("tuxianghuoquchenggong");

            if (stopStatus) {
                mPresenter.baiduToken();
            }
        }
    }

    @Override
    public void getsurplusError(String error) {
        ToastUtils.showShort("未查询到");
        mailName.setText("");
        mailCode.setText("0");
        mailID1 = "";
    }

    @Override
    public void getsurplusSuccess(BaseModel<MailNumberBean> o, String id) {
        if (o.getData() != null) {
            if (o.getData().getQuantity() > 0) {
                mailCode.setText(o.getData().getQuantity() + "");
                mailCode1 = o.getData().getBranchCode();
                mailID1 = id;
//                mailName.setText(o.getData().getBranchName());
                if (mailDialog != null) {
                    mailDialog.dismiss();
                }
            } else {
                ToastUtils.showShort("未查询到");
                mailCode.setText("0");
                mailID1 = "";
                mailName.setText("");
            }
        } else {
            ToastUtils.showShort("未查询到");
            mailCode.setText("0");
            mailID1 = "";
            mailName.setText("");
        }
    }

    @Override
    public void onDataError() {
        playRing("shujuwuxiao.mp3");
    }

    @Override
    public void onUpFail(String mag) {
        dissmissDialog();
        if (mag.equals("1")) {
            shengcheng.setEnabled(true);
            shengcheng.setVisibility(View.VISIBLE);
            MyDialogUtil.showDialog(getActivity(), "单号生成失败");
            playRing("danhaoshibai.mp3");
            return;
        }
        MyDialogUtil.showDialog(getActivity(), mag);
//        playRing("danhaoshibai.mp3");
    }

    @Override
    public void onDestroyView() {
        if (bleScale != null) {
            bleScale.removeOnConnectListener(onConnectListener);
        }
        if (btScale != null) {
            btScale.removeOnConnectBlueListener(onConnectBlueListener);
            btScale.removeOnReceivedDataListener(onReceivedDataListener);
        }
        handler1.removeCallbacksAndMessages(null);
        super.onDestroyView();
        unbinder.unbind();
    }


    MailDialog mailDialog;

    @OnClick({R.id.btn_save, R.id.caozuo, R.id.mailName, R.id.chanpin_dx, R.id.order_type, R.id.shengcheng, R.id.qingkong1, R.id.qingkong2,
            R.id.qingkong3, R.id.lianjie, R.id.kddh, R.id.dayin_img})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_save:
                if ((int) order_type.getTag() == 1) {
                    if (TextUtils.isEmpty(orderID)) {
                        ToastUtil.getInstance()._short(getActivity(), "订单ID不能为空");
                        return;
                    }
                    if (TextUtils.isEmpty(mail_code2.getText().toString().trim())) {
                        ToastUtil.getInstance()._short(getActivity(), "快递单号不能为空");
                        return;
                    }
                    if (TextUtils.isEmpty(mailName.getText().toString().trim())) {
                        ToastUtil.getInstance()._short(getActivity(), "快递名称不能为空");
                        return;
                    }
                    for (int i = 0; i < list.size(); i++) {
                        if ("-1".equals(thStatus)) {
                            for (OrderDetailBean.DataBean1 bean1 : list2) {
                                if (list.get(i).getGoods_model().equals(bean1.getGoods_model()) && Integer.parseInt(bean1.getRetreat_num()) > 0) {
//                                if (isTh(bean1.getGoods_model(), Integer.parseInt(bean1.getRetreat_num()))) {
                                    showError(list.get(i).getGoods_model() + "有退货未处理");
                                    return;
//                                }
                                }
                            }
                        }
                        if (!list.get(i).isSelect()) {
                            ToastUtil.getInstance()._short(getActivity(), "存在产品未验证");
                            return;
                        }
                    }
                    if (!TextUtils.isEmpty(sjzl.getText().toString().trim())) {
                        mPresenter.upOrder(orderID, mail_code2.getText().toString().trim(), (oldSjzl + Integer.parseInt(sjzl.getText().toString().trim().replace("g", ""))) + "",
                                chanpin_dx.getText().toString().trim(), mailID1, "2", content.getText().toString().trim(),
                                mailName.getText().toString().trim(), ((int) order_type.getTag() + 1) + "");
                    } else {
                        mPresenter.upOrder(orderID, mail_code2.getText().toString().trim(), sjzl.getText().toString().trim(),
                                chanpin_dx.getText().toString().trim(), mailID1, "2", content.getText().toString().trim(),
                                mailName.getText().toString().trim(), ((int) order_type.getTag() + 1) + "");
                    }

                    if (!StringUtils.isEmpty(imgUrl))
                        if (stopStatus) {
                            mPresenter.baiduToken();
                        }
                }
                break;
            case R.id.dayin_img:
                if ((int) order_type.getTag() == 0) {
                    if (!ZPLPrinterHelper.IsOpened()) {
                        ToastUtil.getInstance()._short(mContext, "打印机连接失败");
                        return;
                    }
                    if (!dyjStatus) {
                        return;
                    }

                    if (kuaiDiBean != null) {
                        if (TextUtils.isEmpty(kuaiDiBean.getImgBase64())) {
                            showLoading();
                            mPresenter.getKuaiDiImg("1", orderCode, kuaiDiBean.getKuaidinum());
                            return;
                        }
                        daYin();
                    } else {
                        ToastUtil.getInstance()._short(getActivity(), "暂无图片");
                    }
                }
                break;
            case R.id.caozuo:
                getActivity().startActivity(new Intent(getActivity(), OperationRecordActivity.class));
                break;
            case R.id.mailName:
                if ((int) order_type.getTag() == 0) {
                    if (mailList1.size() > 0) {
                        mailDialog = null;
                        mailDialog = new MailDialog(getActivity(), mailList1, mailName, mailCode, mPresenter);
                        mailDialog.show();
                    }
                } else {
                    if (mailList.size() > 0) {
                        mailDialog = null;
                        mailDialog = new MailDialog(getActivity(), mailList, mailName, mailCode);
                        mailDialog.show();
                    }
                }
                break;
            case R.id.chanpin_dx:
                ChiCunDialog chiCunDialog = new ChiCunDialog(getActivity(), chanpin_dx);
                chiCunDialog.show();
                break;
            case R.id.order_type:
                if (scfs == null) {
                    ToastUtil.getInstance()._short(getActivity(), "请输出订单编号");
                    return;
                }
                XPopup.get(getActivity()).asCenterList("请选择单号方式", scfs,
                        new OnSelectListener() {
                            @Override
                            public void onSelect(int position, String text) {
                                order_type.setText(text);
                                order_type.setTag(position);
                                if (position == 0) {
                                    mail_code_ll1.setVisibility(View.VISIBLE);
                                    mail_code_ll2.setVisibility(View.GONE);
                                    btnSave.setText("发货打印");
                                    btnSave.setVisibility(View.GONE);
                                    dayin_img.setVisibility(View.VISIBLE);
                                    for (int i = 0; i < mailList1.size(); i++) {
                                        if (MyApplication.getMailID().equals(mailList1.get(i).getId())) {
                                            mailName.setText(mailList1.get(i).getSon_name());
                                            mailCode1 = mailList1.get(i).getCode();
                                            mailID1 = mailList1.get(i).getId();
                                            templateCode = mailList1.get(i).getTemplate_code();
                                            mPresenter.surplus(mailList1.get(i).getId());
                                            return;
                                        }
                                        if (i == mailList1.size() - 1) {
                                            mailName.setText(mailList1.get(0).getSon_name());
                                            mailCode1 = mailList1.get(0).getCode();
                                            mailID1 = mailList1.get(0).getId();
                                            templateCode = mailList1.get(0).getTemplate_code();
                                            mPresenter.surplus(mailList1.get(0).getId());
                                        }
                                    }
                                } else {
                                    mail_code_ll1.setVisibility(View.GONE);
                                    mail_code_ll2.setVisibility(View.VISIBLE);
                                    btnSave.setText("发货保存");
                                    btnSave.setVisibility(View.VISIBLE);
                                    dayin_img.setVisibility(View.GONE);
                                    for (int i = 0; i < mailList.size(); i++) {
                                        if (MyApplication.getMailCode().equals(mailList.get(i).getId())) {
                                            mailName.setText(mailList.get(i).getName());
                                            mailCode.setText(mailList.get(i).getCode());
                                            mailCode1 = mailList.get(i).getCode();
                                            mailID1 = mailList.get(i).getId();
                                            return;
                                        }
                                        if (i == mailList.size() - 1) {
                                            mailName.setText(mailList.get(0).getName());
                                            mailCode.setText(mailList.get(0).getCode());
                                            mailCode1 = mailList.get(0).getCode();
                                            mailID1 = mailList.get(0).getId();
                                        }
                                    }
                                }
                            }
                        })
                        .show();
                break;
            case R.id.shengcheng:
                if (TextUtils.isEmpty(name)) {
                    ToastUtil.getInstance()._short(getActivity(), "收件人信息不能为空");
                    return;
                }
                if (TextUtils.isEmpty(mobile)) {
                    ToastUtil.getInstance()._short(getActivity(), "收件人信息不能为空");
                    return;
                }
                if (TextUtils.isEmpty(address)) {
                    ToastUtil.getInstance()._short(getActivity(), "收件人信息不能为空");
                    return;
                }
//                if (TextUtils.isEmpty(num.getText().toString().trim())) {
//                    ToastUtil.getInstance()._short(getActivity(), "数量不能为空");
//                    return;
//                }
//                if (TextUtils.isEmpty(chanpin_zl.getText().toString().trim().replace("g", ""))) {
//                    ToastUtil.getInstance()._short(getActivity(), "重量不能为空");
//                    return;
//                }
//                sjzl.setText("800g");
                if (TextUtils.isEmpty(sjzl.getText().toString().trim().replace("g", ""))) {
                    ToastUtil.getInstance()._short(getActivity(), "实际重量不能为空");
                    return;
                }
                if (StringUtils.equalsIgnoreCase(sjzl.getText().toString().trim().replace("g",
                        ""), "0")) {
                    ToastUtil.getInstance()._short(getActivity(), "实际重量不能为空");
                    return;
                }
                if (TextUtils.isEmpty(templateCode)) {
                    ToastUtil.getInstance()._short(getActivity(), "请前往后台完善" + mailName.getText().toString().trim() + "信息");
                    return;
                }
                if (TextUtils.isEmpty(mailID1)) {
                    ToastUtil.getInstance()._short(getActivity(), "快递公司编码不能为空");
                    return;
                }
                for (int i = 0; i < list.size(); i++) {
                    if ("-1".equals(thStatus)) {
                        for (OrderDetailBean.DataBean1 bean1 : list2) {
                            if (list.get(i).getGoods_model().equals(bean1.getGoods_model()) && Integer.parseInt(bean1.getRetreat_num()) > 0) {
//                                if (isTh(bean1.getGoods_model(), Integer.parseInt(bean1.getRetreat_num()))) {
                                showError(list.get(i).getGoods_model() + "有退货未处理");
                                return;
//                                }
                            }
                        }
                    }
                    if (!list.get(i).isSelect()) {
                        ToastUtil.getInstance()._short(getActivity(), "存在产品未验证");
                        return;
                    }
                }
                if (TextUtils.isEmpty(orderID)) {
                    ToastUtil.getInstance()._short(getActivity(), "订单ID不能为空");
                    return;
                }
                if (TextUtils.isEmpty(mailName.getText().toString().trim())) {
                    ToastUtil.getInstance()._short(getActivity(), "快递名称不能为空");
                    return;
                }
                System.out.println(templateCode);
                shengcheng.setEnabled(false);
                shengcheng.setVisibility(View.INVISIBLE);
//                kuaiDiBean = null;
                if (kuaiDiBean != null) {
                    kuaiDiBean.setImgBase64("");
                    kuaiDiBean.setKuaidinum("");
                }
                showLoading();
                mPresenter.getKuaiDiCode(name, mobile, address, all_count, sjzl.getText().toString().trim().replace("g", ""), mailName.getText().toString().trim(), content.getText().toString().trim(),
                        templateCode, orderID, mailID1);
                break;
            case R.id.qingkong1:
//                handler1.removeMessages(1);
                mail_code1.setText("");
                shengcheng.setEnabled(true);
                shengcheng.setVisibility(View.VISIBLE);
                chanpin_dx.setEnabled(true);
                lianjie.setEnabled(true);
                mailName.setEnabled(true);
                order_type.setEnabled(true);
                orderid.setText("");
                orderid.setBackgroundResource(R.drawable.et_yellow);
                list.clear();
                adapter.clear();
                adapter.notifyDataSetChanged();
                list2.clear();
                adapter2.clear();
                adapter2.notifyDataSetChanged();
                sjzl.setText("");
                chanpin_dx.setText("");
                mail_code2.setText("");
                isBing = false;
                bingdan_ll.setVisibility(View.GONE);
                orderid1.setText("");
                send_out_type.setText("");
                userInfo.setText("");
                content.setText("");
                num.setText("");
                all_count = "";
                chanpin_zl.setText("");
                name = "";
                mobile = "";
                address = "";
                orderID = "";
                if (kuaiDiBean != null) {
                    kuaiDiBean.setImgBase64("");
                    kuaiDiBean.setKuaidinum("");
                }
//                for (int i = 0; i < mailList1.size(); i++) {
//                    if (MyApplication.getMailID().equals(mailList1.get(i).getId())) {
//                        mailName.setText(mailList1.get(i).getSon_name());
//                        mailCode.setText("");
//                        mailCode1 = mailList1.get(i).getCode();
//                        mailID1 = mailList1.get(i).getId();
//                        templateCode = mailList1.get(i).getTemplate_code();
//                        return;
//                    }
//                }
                playRing("qingkong.mp3");
                break;
            case R.id.qingkong2:
                sjzl.setText("");
                playRing("qingkong.mp3");
                break;
            case R.id.qingkong3:
                mail_code1.setText("");
                mail_code2.setText("");
                playRing("qingkong.mp3");
                break;
            case R.id.lianjie:
                if (!select)
                    if (TextUtils.isEmpty(chanpin_zl.getText().toString().trim())) {
                        return;
                    }
                float value = 0;
                if (!TextUtils.isEmpty(chanpin_zl.getText().toString())) {
                    Float.valueOf(chanpin_zl.getText().toString().replace("g", ""));
                }
                EditDialog editDialog = new EditDialog(getActivity(), sjzl, value
                        , select);
                editDialog.show();
                handler.removeCallbacks(runnable);
//                if (mBluetoothAdapter.isDiscovering()) {
//                    mBluetoothAdapter.cancelDiscovery();
//                }
//                mBluetoothAdapter.startDiscovery();
                break;
            case R.id.kddh:
                if (kuaiDiBean != null) {
                    ImgDialog imgDialog = new ImgDialog(getActivity(), kuaiDiBean.getImgBase64());
                    imgDialog.show();
                } else {
                    ToastUtil.getInstance()._short(getActivity(), "暂无图片");
                }
                break;
        }
    }

    public void daYin() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Bitmap bitmap = GlideImageLoader.getBitmap(BaseUrl.url1 + kuaiDiBean.getImgBase64());
                    if (bitmap == null) {
                        if (TextUtils.isEmpty(kuaiDiBean.getImgBase64())) {
                            ToastUtil.getInstance()._short(mContext, "获取图片失败");
                        } else {
                            ToastUtil.getInstance()._short(mContext, "网络下载失败");
                        }
                    }
                    if (TextUtils.isEmpty(MainActivity.userInfoBean.getPrint_paper_width())) {
                        ToastUtil.getInstance()._short(mContext, "纸张宽度不能为空");
                        return;
                    }
                    if (TextUtils.isEmpty(MainActivity.userInfoBean.getPrint_deviation_x())) {
                        ToastUtil.getInstance()._short(mContext, "水平偏移不能为空");
                        return;
                    }
                    if (TextUtils.isEmpty(MainActivity.userInfoBean.getPrint_deviation_y())) {
                        ToastUtil.getInstance()._short(mContext, "垂直偏移不能为空");
                        return;
                    }
                    MainActivity.mZPL.start();
                    MainActivity.mZPL.printData("^LL" + bitmap.getHeight() + "\r\n");
                    MainActivity.mZPL.PW(MainActivity.userInfoBean.getPrint_paper_width());
                    MainActivity.mZPL.printBitmap(MainActivity.userInfoBean.getPrint_deviation_x(),
                            MainActivity.userInfoBean.getPrint_deviation_y(), bitmap);
                    int i = MainActivity.mZPL.end();
                    Looper.prepare();
                    if (i == 0) {
                        DayinDialog1 dayinDialog1 = new DayinDialog1(getActivity(), i + "");
                        dayinDialog1.show();
                        dayinDialog1.setOnDismissListener(new DialogInterface.OnDismissListener() {
                            @Override
                            public void onDismiss(DialogInterface dialog) {
                                handler.sendEmptyMessage(2);
                            }
                        });
                        playRing("dayinwancheng.mp3");
                    } else {
                        DayinDialog2 dayinDialog2 = new DayinDialog2(getActivity(), i + "");
                        dayinDialog2.show();
                        dayinDialog2.setOnDismissListener(new DialogInterface.OnDismissListener() {
                            @Override
                            public void onDismiss(DialogInterface dialog) {
//                                                handler.sendEmptyMessage(2);
                            }
                        });
                        playRing("dayinshibai.mp3");
                    }
                    Looper.loop();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    public void onBarcodeEvent(String code) {
        System.out.println("扫描结果1：" + code);
        if (TextUtils.isEmpty(orderid.getText().toString().trim())) {
            orderCode = code;
            if (kuaiDiBean != null) {
                kuaiDiBean.setImgBase64("");
                kuaiDiBean.setKuaidinum("");
            }
            mPresenter.Into38(code);
        } else {
            Message message = new Message();
            message.obj = code;
            message.what = 1;
            handler.sendMessage(message);
        }
    }

    private AssetManager assetManager;
    private MediaPlayer player = new MediaPlayer();

    private void playRing(String fileName) {
        try {
            assetManager = getActivity().getAssets();
            AssetFileDescriptor fileDescriptor = assetManager.openFd(fileName);
//            if (player.isPlaying()) {
            player.reset();
//            }
            player.setDataSource(fileDescriptor.getFileDescriptor(), fileDescriptor.getStartOffset(),
                    fileDescriptor.getLength());
            player.prepare();
            player.start();
            player.setOnSeekCompleteListener(new MediaPlayer.OnSeekCompleteListener() {
                @Override
                public void onSeekComplete(MediaPlayer mp) {
                    player.stop();
                }
            });

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void playUrl(String fileName, final int i) {
        if (TextUtils.isEmpty(fileName)) {
            if (i == 1) {
                playRing("luruchenggong.mp3");
                return;
            } else {
                playRing("wuxiao.mp3");
                return;
            }
        }
        try {
            player.reset();
            if (!fileName.contains("http")) {
                player.setDataSource(BaseUrl.mp3Url + fileName);
            } else {
                player.setDataSource(fileName);
            }
            player.prepare();
            player.start();
            player.setOnSeekCompleteListener(new MediaPlayer.OnSeekCompleteListener() {
                @Override
                public void onSeekComplete(MediaPlayer mp) {
                    if (i == 1) {
                        playRing("luruchenggong.mp3");
                    } else {
                        playRing("wuxiao.mp3");
                    }
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onPause() {
        if (player.isPlaying()) {
            player.stop();
        }
        super.onPause();
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onDestroy() {
        player.release();
        handler1.removeMessages(1);
        super.onDestroy();
    }

    public static Bitmap setImage(String imageStr) {
        byte[] decode = Base64.decode(imageStr, Base64.DEFAULT);
        return BitmapFactory.decodeByteArray(decode, 0, decode.length);
    }

    public void getDayinStatus() {
        try {
            MainActivity.mZPL.WriteData("~HQES\r\n".getBytes());
            String str = byteToString(MainActivity.mZPL.ReadData(2)).replace("PRINTER STATUS ERROR:", "");
            if (str.length() > 0 && str.substring(0, 1).equals("0")) {
                dyjStatus = true;
                dayin_img.setImageResource(R.mipmap.dayin_true);
                if ((MyApplication.isDyPlay == 0 || MyApplication.isDyPlay == 2) && !MyApplication.dy_scaleIsConnect) {
                    MyApplication.isDyPlay = 1;
                    MyApplication.dy_scaleIsConnect = true;
                    playRing("lianjiesuccess.mp3");
                }
//                System.out.println("1111111111111:" + str);
            } else {
                dyjStatus = false;
                dayin_img.setImageResource(R.mipmap.dayin_false);
                if ((MyApplication.isDyPlay == 1) && MyApplication.dy_scaleIsConnect) {
                    MyApplication.isDyPlay = 2;
                    MyApplication.dy_scaleIsConnect = false;
                    playRing("lianjieerror.mp3");
                }
//                System.out.println("2222222222222:" + str);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private static String byteToString(byte[] bytes) {
        if (null == bytes || bytes.length == 0) {
            return "";
        }
        String strContent = "";
        try {
            strContent = new String(bytes, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return strContent;
    }

    private BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
        @Override
        public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            super.onCharacteristicRead(gatt, characteristic, status);
            Log.i("TAG", "000000:");
            if (status == BluetoothGatt.GATT_SUCCESS) {
                // 收到的数据
                byte[] receiveByte = characteristic.getValue();
                Log.i("TAG", "1111:" + receiveByte.toString());
            } else {
                Log.d("TAG", "接收数据失败-->" + status);
            }
        }

        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            super.onConnectionStateChange(gatt, status, newState);
            if (newState == BluetoothProfile.STATE_CONNECTED) {
                Log.i("TAG", "连接成功");
                mBluetoothGatt.discoverServices();
            } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
                Log.d("TAG", "连接失败-->" + status);
            }
        }

        @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {//发现服务，在蓝牙连接的时候会调用
            Log.e("onCharacteristicRead中", "333333333333333");
        }

        @Override
        public void onDescriptorRead(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {//descriptor读
            Log.e("onCharacteristicWrite中", "数据接收了哦22222222222222222");
        }

        @Override
        public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {// Characteristic 改变，数据接收会调用
            Log.e("onCharacteristicWrite中", "数据接收了哦11111111111");
        }
    };


    private final static String TAG = MainActivity.class.getSimpleName();
    final Boolean SendMoudle = true;  //  这个表示是连接称重模块
    Boolean bisClosed = false;
    //    public ScaleView scaleView;
    Bundle bundle;
    private SQLiteDatabase mydb;
    static int dbversion = 1;
    private static final int PERMISSION_REQUEST_COARSE_LOCATION = 1;
    private BluetoothAdapter mBluetoothAdapter = null;
    public Bluetooth_Scale btScale = null;
    public BluetoothLeClass bleScale = null;
    int BluetoothType;
    Boolean b_scaleIsConnect = Boolean.FALSE;
    SCALENOW scalenow = new SCALENOW();
    String BluetoothAddress;

    public void getBle() {
        try {
            mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        } catch (Exception e) {
            e.printStackTrace();
        }
        // Checks if Bluetooth is supported on the device.
        if (mBluetoothAdapter == null) {
            ToastUtil.getInstance()._short(getActivity(), "不支持蓝牙");
            return;
        }

        mBluetoothAdapter.enable();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (getActivity().checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                builder.setTitle("此应用需要位置访问权限");
                builder.setMessage("请授予位置访问权限，以便此应用可以检测蓝牙。");
                builder.setPositiveButton(android.R.string.ok, null);
                builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialog) {
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                            requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, PERMISSION_REQUEST_COARSE_LOCATION);
                        }
                    }
                });
                builder.show();
            }
        }
        btScale = Bluetooth_Scale.getBluetooth_scale();
        btScale.setOnReceivedDataListener(onReceivedDataListener);
        btScale.setOnConnectBlueListener(onConnectBlueListener);
        if (bleScale == null) {
            bleScale = BluetoothLeClass.getBluetoothLeClass();
            bleScale.setOnConnectListener(onConnectListener);
            bleScale.setOnDataAvailableListener(new BluetoothLeClass.OnDataAvailableListener() {
                @Override
                public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {

                }

                @Override
                public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
                    byte[] buffer = characteristic.getValue();
                    OnReceivedData(buffer);
                }
            });
        }
        ReadConfig();
//        ChkAndConnectBl();
    }

    public BluetoothLeClass.OnConnectListener onConnectListener = new BluetoothLeClass.OnConnectListener() {
        @Override
        public void onConnect(BluetoothGatt gatt, int type) {
            if (type == 0) {
                MyApplication.b_scaleIsConnect = true;
            } else if (type == 1) {
                MyApplication.b_scaleIsConnect = false;
            }
            handler1.sendEmptyMessage(2);
        }
    };
    public Bluetooth_Scale.onReceivedDataListener onReceivedDataListener = new Bluetooth_Scale.onReceivedDataListener() {

        @Override
        public void onReceivedData(byte[] buf) {
            OnReceivedData(buf);
        }
    };
    public Bluetooth_Scale.onConnectBlueListener onConnectBlueListener = new Bluetooth_Scale.onConnectBlueListener() {
        @Override
        public void onConnect(int what, int arg) {
            if (arg < 2) {
                MyApplication.b_scaleIsConnect = Boolean.FALSE;
            } else {
                MyApplication.b_scaleIsConnect = Boolean.TRUE;
            }
            handler1.sendEmptyMessage(2);
        }
    };
    byte[] strdata = new byte[100];
    int pStrdata = 0;
    String oldWeight = "0";

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
//                        scaleView.setUnit(scalenow.sUnit);
            if (scalenow.bOverFlag) {
                sjzl.setText("");
            } else {
                if (!oldWeight.equals("0")) {
                    sjzl.setText(scalenow.sformatNetWeight + "g");
                }

                if (!scalenow.sformatNetWeight.equals("0")) {
                    lianjie.setEnabled(false);
                } else {
                    lianjie.setEnabled(true);
                }
                oldWeight = scalenow.sformatNetWeight;
            }

//                        scaleView.setZero(scalenow.bZeroFlag);
//                        scaleView.setStable(scalenow.bWeiStaFlag);
        }
    };

    void OnReceivedData(byte buf[]) {
        int bytes = buf.length;
        boolean result = false;
        for (int i = 0; i < bytes; i++) {
            if (buf[i] == 0x2) pStrdata = 0;
            else if ((buf[i] == 0x0a) || (buf[i] == 0x03)) {
                GetWeight(strdata, pStrdata);
                result = true;
                pStrdata = 0;
            } else {
                strdata[pStrdata] = buf[i];
                if (++pStrdata >= 100) pStrdata = 0;
            }
        }
        if (result)
            handler1.post(runnable);
    }

    void ChkAndConnectBl() {
        if (BluetoothAddress.length() > 0) {
            //ble或者双模模块
            if ((BluetoothType == BluetoothDevice.DEVICE_TYPE_LE)) {
                if ((bleScale != null) && bleScale.isConnect) {
                    bleScale.disconnect();
                }
                bleScale.connect(BluetoothAddress);
            } else {
                BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(BluetoothAddress);
                if (device != null) {
                    btScale.connect(device);
                }
            }
        }
    }

    protected void onActivityResult1(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 0:
                if (resultCode == RESULT_OK) {
                    Intent serverIntent = new Intent(getActivity(), DeviceListActivity.class);
                    startActivityForResult(serverIntent, 1);
                }
                break;
            case 1:
                if (resultCode == RESULT_OK) {
                    //String name=data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_NAME);
                    BluetoothAddress = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
                    BluetoothType = data.getExtras().getInt(DeviceListActivity.EXTRA_DEVICE_TYPE);
                    if (BluetoothAddress.length() > 0) {
                        //ble或者双模模块
                        if ((BluetoothType == BluetoothDevice.DEVICE_TYPE_LE)) {
                            if ((bleScale != null) && bleScale.isConnect) {
                                bleScale.disconnect();
                            }
                            bleScale.connect(BluetoothAddress);
                            WriteConfig();
                        } else {
                            BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(BluetoothAddress);
                            if (device != null) {
                                btScale.connect(device);
                                WriteConfig();
                            }
                        }
                    }
                }
                break;
        }
    }

    void GetWeight(byte[] databuf, int datalenght) {
        float f = 0;
        int dot = 1;
        scalenow.bOverFlag = false;
        scalenow.bWeiStaFlag = false;
        switch (databuf[0]) {
            case 'o':
            case 'O':
                scalenow.bOverFlag = true;
                break;
            case 'u':
            case 'U':
                scalenow.bWeiStaFlag = false;
                break;
            case 's':
            case 'S':
                scalenow.bWeiStaFlag = true;
                break;
        }
        if (datalenght > 7) {
            for (int i = 0; i < 7; i++) {
                if (databuf[i + 6 + 1] == '.') {
                    dot = -1;
                } else {
                    if (dot >= 0) {
                        f = f * 10 + ((databuf[i + 6 + 1] == ' ') ? 0 : (databuf[i + 6 + 1] - '0'));
                    } else {
                        f += Math.pow(10, dot) * (databuf[i + 6 + 1] - '0');
                        dot--;
                    }
                }
            }
            if (databuf[6] == '-') f *= -1;
        }
        if (dot < 0) dot = (-dot) - 1;
        else dot = 0;
        scalenow.fformatNetWeight = f;
        scalenow.sformatNetWeight = String.format("%1." + String.valueOf(dot) + "f", f);
        if (datalenght > 14) {
            scalenow.sUnit = new String(databuf, 14, datalenght - 14);
        }
        scalenow.bZeroFlag = (f == 0);
    }

    public void ReadConfig() {
        SharedPreferences settings = getActivity().getSharedPreferences(PubFunction.PREFS_NAME, Context.MODE_PRIVATE);
        BluetoothAddress = settings.getString("BluetoothAddress", "");
        BluetoothType = settings.getInt("BluetoothType", 0);
    }

    public void WriteConfig() {

        SharedPreferences settings = getActivity().getSharedPreferences(PubFunction.PREFS_NAME, 0);
        SharedPreferences.Editor editor = settings.edit();
        editor.putInt("BluetoothType", BluetoothType);
        editor.putString("BluetoothAddress", BluetoothAddress);
        editor.commit();
    }

    public static class SCALENOW {
        public String sformatNetWeight = "0";
        public String sUnit = " g ";
        public float fformatNetWeight;
        public boolean bZeroFlag;
        public boolean bWeiStaFlag;
        public boolean bOverFlag;
    }
}
